package view;

import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

import net.HTTPDownloader;
import util.IView;
import util.LoggingUtils;

public class DownloadProgressBar extends JProgressBar implements IView {
	private String	filename;

	//RBB
	protected final String className = this.getClass().getName();
	
	public DownloadProgressBar() {
		HTTPDownloader.getInstance().addView(this);
		this.setStringPainted(true);
		this.filename = "";
	}

	@Override
	public void updateView(final Object obj, final Object additionalInformation) {
		final String classMethod = className + ".updateView(Object)";
		LoggingUtils.logStart(classMethod + " with parameter of type " + obj.getClass().getName());
		// invoke the Swing thread to change the UI
		Runnable updateUIRunnable = new Runnable() {

			@Override
			public void run() {
				LoggingUtils.logStart("run() of Runnable to updateUI of Download Progress Bar in " + classMethod);
				DownloadProgressBar.this.updateUI(obj, additionalInformation);
				LoggingUtils.logEnd("run() of Runnable to updateUI of Download Progress Bar in " + classMethod);
			}
		};
		LoggingUtils.logStart("invokeLater of Runnable to updateUI of Download Progress Bar in " + classMethod);
		SwingUtilities.invokeLater(updateUIRunnable);
		LoggingUtils.logEnd(classMethod);
	}

	private void updateUI(Object obj, Object additionalInformation) {
		if (obj instanceof String && ((String) obj).equals("show") && obj instanceof String) {
			this.setVisible(true);
			this.filename = (String) additionalInformation;
		} else if (obj instanceof String && ((String) obj).equals("hide")) {
			this.setVisible(false);
		} else if (obj instanceof Integer) {
			this.setValue((Integer) obj);
			if (additionalInformation instanceof Integer) {
				this.setMaximum((Integer) additionalInformation);
			}
		}

		this.setString(String.format("%s: %d/%d Kbytes", this.filename, this.getValue() >> 10, this.getMaximum() >> 10));
		this.revalidate();
		this.repaint();
	}

}
